document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('loginForm');
    const errorMessages = document.querySelectorAll('.error-message');
    const togglePassword = document.querySelector('.toggle-password');
    const passwordInput = document.getElementById('password');


    if (togglePassword && passwordInput) {
        togglePassword.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            this.classList.toggle('show');
            this.setAttribute('aria-label', type === 'password' ? '显示密码' : '隐藏密码');
        });
    }

    function clearAllErrors() {
        errorMessages.forEach(element => {
            element.textContent = '';
        });
        document.querySelectorAll('.form-group input').forEach(input => {
            input.classList.remove('error');
        });
    }

    
    function showError(inputId, message) {
        const input = document.getElementById(inputId);
        if (input) {
            const errorElement = input.parentElement.querySelector('.error-message');
            errorElement.textContent = message;
            input.classList.add('error');
        }
    }

    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        clearAllErrors();

        const username = document.getElementById('username');
        const password = document.getElementById('password');
        let isValid = true;
        if (!validateUsername(username.value)) {
            showError('username', '用户名必须以字母开头');
            isValid = false;
        }

        if (!validatePassword(password.value)) {
            showError('password', '密码长度必须在6-8个字符之间');
            isValid = false;
        }

        if (isValid) {
            const formData = new FormData();
            formData.append('username', username.value);
            formData.append('password', password.value);

            fetch('../php/login.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    
                        localStorage.setItem('xlsystem_user', JSON.stringify({
                            id: data.data.user.id,
                            username: data.data.user.username
                        }));
                        alert(data.message);
                        window.location.href = '../html/home.html';
                } else {
                    if (data.errors) {
                        Object.entries(data.errors).forEach(([field, message]) => {
                            if (field === 'auth') {
                                showError('username', message);
                            } else {
                                showError(field, message);
                            }
                        });
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('username', '系统错误，请稍后重试');
            });
        }
    });
});
